package com.sleepingcat.ft_flutter.service

import android.content.Context
import android.content.Intent
import androidx.activity.result.ActivityResultLauncher
import androidx.fragment.app.FragmentActivity
import com.cat.android.lib_base.base.IRouterActivity
import com.cat.android.lib_ui.widget.CommonDialog
import com.google.auto.service.AutoService
import com.idlefish.flutterboost.FlutterBoost
import com.sleepingcat.ft_flutter.activity.MyFlutterActivity
import com.sleepingcat.ft_flutter.activity.MyTransparentFlutterActivity
import com.sleepingcat.ft_flutter.fragment.MyFlutterFragment
import com.sleepingcat.lib_common.const.Routes
import com.sleepingcat.lib_common.service.IFlutter
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume

/**
 * @作者 志浩
 * @时间 2025/5/1 21:59
 * @描述 TODO
 */
@AutoService(IFlutter::class)
class FlutterImpl : IFlutter, CoroutineScope by MainScope() {
    private val TAG = "FlutterImpl"

    // 原生跳flutter接口
    override fun navigate(context: Context, url: String, argument: Map<String, Any>?, opaque: Boolean) {
        if (opaque) {
            MyFlutterActivity.startActivity(context, null, url, argument)
        } else {
            MyTransparentFlutterActivity.startActivity(context, null, url, argument)
        }
    }

    override fun navigateForResult(context: Context, url: String, argument: Map<String, Any>?, opaque: Boolean, launcher: ActivityResultLauncher<Intent>) {
        if (opaque) {
            MyFlutterActivity.startActivityForResult(context, null, url, argument, launcher)
        } else {
            MyTransparentFlutterActivity.startActivityForResult(context, null, url, argument, launcher)
        }
    }

    override suspend fun showNativeNormalDialog(title: String, content: String): Boolean {
        val currentActivity = FlutterBoost.instance().currentActivity()
        if (currentActivity is FragmentActivity) {
            suspend fun normalDialog(): Boolean = suspendCancellableCoroutine<Boolean> {
                CommonDialog(currentActivity)
                    .requireTitle(title)
                    .requireMessage(content)
                    .requireNegative { dialog ->
                        it.resume(false)
                        dialog?.dismiss()
                    }
                    .requirePositive { dialog ->
                        it.resume(true)
                        dialog?.dismiss()
                    }
                    .show(currentActivity.supportFragmentManager, null)
            }
            return normalDialog()
        } else {
            return false;
        }
    }

    override suspend fun showNativeInputDialog(title: String, content: String, hint: String): String {
        val currentActivity = FlutterBoost.instance().currentActivity()
        if (currentActivity is FragmentActivity) {
            suspend fun inputDialog(): String = suspendCancellableCoroutine<String> {
                var text = ""
                CommonDialog(currentActivity)
                    .requireTitle(title)
                    .requireEdit(text = content, hint = hint) {
                        text = it?.toString() ?: ""
                    }
                    .requireNegative { dialog ->
                        it.resume(text)
                        dialog?.dismiss()
                    }
                    .requirePositive { dialog ->
                        it.resume(text)
                        dialog?.dismiss()
                    }
                    .show(currentActivity.supportFragmentManager, null)
            }
            return inputDialog()
        } else {
            return ""
        }
    }

    override suspend fun showFlutterMsgDialog(title: String, content: String): Boolean {
        suspend fun normalDialog() = suspendCancellableCoroutine<Boolean> {
            val currentActivity = FlutterBoost.instance().currentActivity()
            if (currentActivity is IRouterActivity) {
                currentActivity.topFragment().navigateWithResult(
                    resId = Routes.SingleFlutterFragment.SINGLE_FLUTTER_FRAGMENT.hashCode(),
                    requestCode = "msgDialog",
                    args = MyFlutterFragment.createArgument(uniqueId = null, url = "ui/msgDialog", requestCode = "msgDialog", urlParams = hashMapOf("title" to title, "content" to content), opaque = false),
                    optsBuilder = { builder ->
                        builder.setExitAnim(-1)
                        builder.setEnterAnim(-1)
                        builder.setPopExitAnim(-1)
                        builder.setPopEnterAnim(-1)
                        builder
                    }
                ) { code, bundle ->
                    val result = bundle.getBoolean("confirm", false)
                    it.resume(result)
                }
            } else {
                it.resume(false)
            }
        }
        return try {
            normalDialog()
        } catch (e: Exception) {
            false
        }
    }

    override suspend fun showFlutterInputDialog(title: String, content: String, hint: String): String {
        suspend fun inputDialog() = suspendCancellableCoroutine<String> {
            val currentActivity = FlutterBoost.instance().currentActivity()
            if (currentActivity is IRouterActivity) {
                currentActivity.topFragment().navigateWithResult(
                    resId = Routes.SingleFlutterFragment.SINGLE_FLUTTER_FRAGMENT.hashCode(),
                    requestCode = "inputDialog",
                    args = MyFlutterFragment.createArgument(uniqueId = null, url = "ui/inputDialog", requestCode = "inputDialog", urlParams = hashMapOf("title" to title, "content" to content, "hint" to hint), opaque = false),
                    optsBuilder = { builder ->
                        builder.setExitAnim(-1)
                        builder.setEnterAnim(-1)
                        builder.setPopExitAnim(-1)
                        builder.setPopEnterAnim(-1)
                        builder
                    }
                ) { code, bundle ->
                    val result = bundle.getString("string", "")
                    it.resume(result)
                }
            } else {
                it.resume("false")
            }
        }
        return try {
            inputDialog()
        } catch (e: Exception) {
            ""
        }
    }
}